import { _decorator, Component, Node, MeshRenderer } from 'cc';
const { ccclass, property, executeInEditMode } = _decorator;

let atlasWith = 512;
let altasHeight = 512;
let paddingLeft = 10;
let paddingTop = 10;
let gap = 4;

let texWidth = 120;
let texHeight = 60;
let maxCols = 3;

let scaleU = texWidth / atlasWith;
let scaleV = texHeight / altasHeight;

@ccclass('BallUVSetter')
@executeInEditMode
export class BallUVSetter extends Component {
    @property
    ballId: number = 0;

    _lastBallId: number = -1;

    start() {
        this.setTilingOffset(this.ballId);
    }

    setTilingOffset(ballId: number) {
        let col = ballId % maxCols
        let row = Math.floor(ballId / maxCols)
        let tx = paddingLeft + col * (texWidth + gap)
        let ty = paddingTop + row * (texHeight + gap)
        let offsetU = tx / atlasWith;
        let offsetV = ty / altasHeight;
        let meshRenderer = this.node.getComponent(MeshRenderer);
        meshRenderer.setInstancedAttribute('a_tilingOffset', [scaleU, scaleV, offsetU, offsetV]);
    }

    update(deltaTime: number) {
        if (this._lastBallId != this.ballId) {
            this.setTilingOffset(this.ballId);
            this._lastBallId = this.ballId;
        }
    }
}


